package com.chuanghai.light.tcp;

public class Packet {
    public static final byte MESSAGE_STX1 = (byte) 0x24;
    public static final byte MESSAGE_STX2 = (byte) 0x58;
    public static final byte MESSAGE_STX3 = (byte) 0x5A;

    public int type;
    public int len;

    public Payload payload;

    public void setPayloadLength(int payloadLength) {
        len = payloadLength;
        payload = new Payload(payloadLength);
    }

    public boolean payloadIsFilled() {
        return payload.size() >= len;
    }

    public byte generateCRC() {
//        byte result = (byte) ((byte) from + (byte) to + (byte) type);
//        payload.resetIndex();
//        final int payloadSize = payload.size();
//        for (int i = 0; i < payloadSize; i++) {
//            result ^= payload.getByte();
//        }
//        fcs = result;
        return 0;
    }

    public void toBytes(byte[] bytes) {
        bytes[0] = MESSAGE_STX1;
        bytes[1] = MESSAGE_STX2;
        bytes[2] = MESSAGE_STX3;
        bytes[3] = (byte) type;
        bytes[4] = (byte) ((len>>8)&0x00ff);
        bytes[5] = (byte) (len&0x00ff);
        payload.resetIndex();
        final int payloadSize = payload.size();
        for (int i = 0; i < payloadSize; i++) {
            bytes[i + 6] = payload.getByte();
        }
    }
}
